package com.bing.bingPro.controller.datebase;

import com.bing.bingPro.controller.fiveOrder.DatabaseConnectionTester;
import com.bing.bingPro.entity.DbConnectionInfo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/db")
public class DatabaseConnectionController {
    private final DatabaseConnectionTester databaseConnectionTester;

    // 可以通过依赖注入DatabaseConnectionTester
    public DatabaseConnectionController(DatabaseConnectionTester databaseConnectionTester) {
        this.databaseConnectionTester = databaseConnectionTester;
    }

    @PostMapping("/test-connection")
    public ResponseEntity<String> testConnection(@RequestBody DbConnectionInfo dbConnectionInfo) {
        try {
            boolean isConnected = DatabaseConnectionTester.testDatabaseConnection(dbConnectionInfo);
            if (isConnected) {
                return ResponseEntity.ok("数据库连接测试成功！");
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("数据库连接测试失败！");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("数据库连接测试时发生异常！");
        }
    }
}
